<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <ul id="test">
      <span>aaa</span>
      <li>bbbb</li>
      <li>cccc</li>
  </ul>
  <script>
    /* 
    绑定事件监听的通用函数(不带委托)
    */
    function bindEvent1 (ele, type, fn) {
      ele.addEventListener(type, fn)
    }

    /* 
    绑定事件监听的通用函数(带委托)
    */
    function bindEvent2(ele, type, fn, selector) {

      ele.addEventListener(type, event => {
        // 得到发生事件的目标
        const target = event.target
        if (selector) {
          // 如果元素被指定的选择器字符串选择, 返回true; 否则返回false。
          if (target.matches(selector)) {
            // 委托绑定调用
            fn.call(target, event)
          } 
        } else {
          // 普通绑定调用
          fn.call(ele, event)
          // fn(event) // this不对
        }
      })
    }


    const ul = document.getElementById('test')
        
    bindEvent2(ul, 'click', function (event) {
      console.log(this)
      alert(event.target.innerHTML)
    }, 'li')
    // bindEvent2(ul, 'click', function (event)  {
    //   console.log(this)
    //   alert(event.target.innerHTML)
    // })
  </script>
</body>
</html>